<?php
class Model_Experts extends Model {
	/**
	 * 专家领域的hash数组
	 * @var unknown_type
	 */
	public  $hashDomain;
	/**
	 * 专家领域的下拉选框数组
	 * @var unknown_type
	 */
	public  $optionDomain;

	/**
	 * 专家类型的hash数组
	 * @var unknown_type
	 */
	public  $hashType;
	
	function photoUrl($photo){
		return URL_WEB . "Upload/experts/photo/$photo";
	}
	
    function __construct(){
    	
    	parent::__construct();
    	//更新用户活跃度
    	$this->updateCredit();
    	
    	$this->optionDomain = M("ExpertsDomain")->getOptionGroup();
    	$this->hashType = Helper_Array::to_hashmap(M("ExpertsType")->select(),'id','name');
    	$this->hashDomain = M("ExpertsDomain")->getHash();
    }
    
    
    function save($data){

    	//上传文件
    	$uploader = new Helper_FileUploader();

		$allowExts = 'jpg,png,gif';
		$maxSize = 300 * 1024; // 300KB
		$uploadDir = PATH_APP_UPLOAD . 'experts/photo/';
		
		$uploader = new Helper_FileUploader();
		$files =& $uploader->getFiles();
		
		foreach ($files as $file) {
			if (!$file->check($allowExts, $maxSize)) {
				// 上传的文件类型不符或者超过了大小限制。
				_message("你上传的文件类型不符或者超过了大小限制。");
				return false;
			}
			// 生成唯一的文件名（重复的可能性极小）
			$filename =  empty($data['uid']) ? _toUniqueId($data) : $data['uid'];
			$filename = $filename . '.' . strtolower($file->getExt());
			$file->move($uploadDir . '/' . $filename);
			
			$data['photo'] = $filename;
		}

		M('ExpertsDomainMap')->save( $data['uid'],$data['domain']);
		
		$data['domain'] = ',' . implode(',',$data['domain']).',';
		
    	parent::save($data);
    }
    /**
     *在读取每条数据后，将domain,type的id转为名称 
     **/
	protected function _after_select_fetch(&$row){

		$row['type'] && $row['_type'] = $this->hashType[$row['type']];
		if(isset($row['domain'])){
			//$row['domain'] = M('ExpertsDomainMap')->getDomainsByUser($row['uid']);
			
			$row['domain'] = explode(',',$row['domain']);
			array_shift($row['domain']);
			array_pop($row['domain']);
			
			unset($tmp);
			foreach ($row['domain'] as $did){
				if($this->hashDomain[$did]){
					$tmp[] = $this->hashDomain[$did];
				}
			}
			$row['_domain'] = implode('、', $tmp);
		}
		if(isset($row['photo'])){
			$row['_photo'] = empty($row['photo']) 
			? $this->photoUrl("nophoto.jpg") 
			: $this->photoUrl($row['photo']);
		}
		
		
	}
	
	function getListByCondition($conditionString){
		$pars = parse_pars($conditionString);
	
		$condition = array();
		$data = array();
		
		$exact = array();
			
		if($pars['type']){
			$exact['type'] = $pars['type'];
		}
		
		$conditions = $this->phaseConditions($like,$exact,$date,$range);
		
    	if (!empty($conditions)){
    		$sql_where .= ' and ' . join(" and ", $conditions);
    	}
		
		if($pars['order']){
			$sql_where .= " order by $pars[order] ";
		} else {
			$sql_where .= " order by name asc ";
		}
		//$pars['perpage']必须先于$pars['limit']的条件处理
		if($pars['perpage']){
			$total = $this->selectCount(" where 1 $sql_where");
			$pager = new Pagination($total,$pars['perpage'],_gp('page','int'));
			$pars['limit'] = "{$pager->minimum} , {$pager->pagesize}";
			$data['pager'] = $pager->display;
		} 

		//$pars['limit']必须后于$pars['perpage']的条件处理
		if($pars['limit']){
			$sql_where .= " limit $pars[limit] ";
		}

		$list = $this->select("*", " where 1 $sql_where");

		foreach ($list as &$row){
			$row['subjectall'] = $row['subject'];
			if($pars['subjectlen']){
				$row['subject'] = _cutstr($row['subject'],$pars['subjectlen'],$pars['subjectdot']);
				if(!$pars['subjectdot'] && (substr($row['subject'], -1) == '.')){
					$row['subject'] = substr($row['subject'], 0, -1);
				}
			}
		}

		if($pars['perpage'] == ""){
			$data = $list;
		} else {
			$data['list'] = $list;
		}
		return $data;
	}
	
	function updateCredit()
	{
		
		//每12个小时执行一次
		if(!_getCache("updateCredit",3600*12)) {
			//获取专家动态数量
			$dynamic_qty_map = M('ExpertsDynamic')->getExpertsDynamicQty();
			
			//获取专家发帖数量
			$bbsMemberTb = M('BbsMember')->getRealTbName();
			$expertsTb = $this->tbName($this->tbName);
			
			$post_qty_map =  $this->selectBySql("select e.uid,b.posts from {$expertsTb} e left join $bbsMemberTb b on e.uid = b.uid");
			$post_qty_map = Helper_Array::to_hashmap($post_qty_map,'uid','posts');
			
			//专家论文,专家新闻 数量需要按每个人去获取
			$data = $this->select("id,uid,name");
			
			foreach ($data as $key=>$row){
				//if($key> 10) break;
				$uid = $row['uid'];
				$name = $row['name'];
				
				$row['dynamic_qty'] =  $dynamic_qty_map[$uid];
				$row['paper_qty'] =  M('Papers')->getExpertPaperQty($name);
				$row['news_qty'] =  M('News')->getExpertNewsQty($name);
				$row['post_qty'] =  $post_qty_map[$uid];
				
				
				$row['credit'] =   1 * $row['dynamic_qty']
								 + 2 * $row['paper_qty']
								 + 1 * $row['news_qty'];
								 + 1 * $row['post_qty'];
				
    			parent::save($row);
				
			}
			_writeCache("updateCredit","Cached!");
		}
	}
}
?>